#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>

#include "../cjson/cJSON.h"

#define MAX_URL_SIZE 256

static char *API_Key = "jgbq1egus7a3fora";
static char *location = "xian";
static char *language = "zh-Hans";
static char unit = 'c';

extern size_t WriteToBuf(void *ptr, size_t size, size_t nmemb, char **result);

void GetWheather(int index)
{
    char url[MAX_URL_SIZE];
    char *buffer = NULL;
    // CURL variables
    CURL *curl;
    CURLcode res;

    sprintf(url, "https://api.seniverse.com/v3/weather/daily.json?key=%s&location=%s&language=%s&unit=%c",
        API_Key, location, language, unit);

    // curl set options and perform
    curl = curl_easy_init();
    if (curl) {
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteToBuf);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer);
        res = curl_easy_perform(curl);
        if (res != CURLE_OK)
            fprintf(stderr, "curl: %s\n", curl_easy_strerror(res));
        curl_easy_cleanup(curl);
    }

    // parse cJSON result and release buffer
    cJSON *root = cJSON_Parse(buffer);
    if (buffer)
        free(buffer);
    if (root) {
        cJSON *tmp;
        tmp = cJSON_GetObjectItem(root, "results")->child;
        tmp = cJSON_GetObjectItem(tmp, "daily");
        tmp = cJSON_GetArrayItem(tmp, index);
        printf("天气：%s\n", cJSON_GetObjectItem(tmp, "text_day")->valuestring);
        printf("温度：%s~%s\n", cJSON_GetObjectItem(tmp, "low")->valuestring,
            cJSON_GetObjectItem(tmp, "high")->valuestring);
        cJSON_Delete(root);
    }
}
